package com.zhongfl.crm.service.impl.boss;

import com.zhongfl.crm.common.BossConsts;
import com.zhongfl.crm.enums.boss.*;
import com.zhongfl.crm.exception.CRMException;
import com.zhongfl.crm.lixiao.mapper.*;
import com.zhongfl.crm.model.boss.*;
import com.zhongfl.crm.service.boss.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.heptagram.channel.api.common.AssertUtils;
import tech.heptagram.core.common.util.JsonUtil;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单管理
 * Created by wangkun23 on 2018/4/11.
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private SequenceService sequenceService;

    @Resource
    private AmibaStaffService amibaStaffService;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderDefaultAssistUserService orderDefaultAssistUserService;

    @Resource
    private OrderAssistUserMapper orderAssistUserMapper;

    @Resource
    private MessageNoticeService messageNoticeService;

    @Resource
    private CommonLogService commonLogService;

    @Resource
    private BankService bankService;

    @Resource
    private OrderMemorandumService orderMemorandumService;

    @Resource
    private OrderTaskLogMapper orderTaskLogMapper;

    @Resource
    private UserWechatMapper userWechatMapper;

    @Resource
    private MessageSendTaskService messageSendTaskService;

    @Resource
    private WorkOrderService workOrderService;

    @Resource
    private OrderCapitalDetailMapper orderCapitalDetailMapper;

    @Resource
    private WorkOrderSettleService workOrderSettleService;

    @Resource
    private CustomerOrderService customerOrderService;

    @Resource
    private RelationAmibaBankService relationAmibaBankService;

    /**
     * 保存订单
     *
     * @param order
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String save(Order order) {
        AssertUtils.notNull(order);
        AssertUtils.hasText(order.getBusinessManagerStaffCode(), "请选择商务经理");
        AssertUtils.hasText(order.getName(), "客户姓名不能为空");
        AssertUtils.notNull(order.getBusinessManagerAmibaId(), "请选择销售阿米巴");

        // 1.订单号
        String orderNo = sequenceService.generateDeliverOrderNo();
        order.setOrderNo(orderNo);
        // 2.订单状态
        order.setStatus(OrderStatus.STATUS_CREATED);
        // 3.订单金额
        if (Objects.nonNull(order.getLoanAmount())) {
            BigDecimal multiply = order.getLoanAmount().multiply(BigDecimal.valueOf(10000));
            order.setLoanAmount(multiply);
        }
        // 4.商务经理
        List<AmibaStaff> salerStaff = amibaStaffService.findByStaffCode(order.getBusinessManagerStaffCode());
        if (CollectionUtils.isEmpty(salerStaff)) {
            throw new CRMException("商务经理: " + order.getBusinessManager() + "(" + order.getBusinessManagerStaffCode() + ")不存在");
        }
        AmibaStaff manager = salerStaff.get(0);
        order.setBusinessManager(manager.getStaffName());
        order.setBusinessManagerMobile(manager.getStaffMobile());

        AmibaStaff assistant = null;
        // 5.跟单助理
        if (StringUtils.isNotEmpty(order.getBusinessAssistantStaffCode())) {
            assistant = amibaStaffService.findSingleByStaffCode(order.getBusinessAssistantStaffCode());
            if (Objects.nonNull(assistant)) {
                order.setBusinessAssistant(assistant.getStaffName());
                order.setAssistantMobile(assistant.getStaffMobile());
            }
        } else {
            order.setBusinessAssistant(manager.getStaffName());
            order.setAssistantMobile(manager.getStaffMobile());
        }
        orderMapper.insertSelective(order);

        //添加默认协作人
        List<OrderDefaultAssistUser> defaultAssistUsers = orderDefaultAssistUserService.findAll();
        if(CollectionUtils.isNotEmpty(defaultAssistUsers)){
            defaultAssistUsers.stream().forEach(e -> {
                OrderAssistUser orderAssistUser = new OrderAssistUser();
                orderAssistUser.setCreatedBy("SYSTEM");
                orderAssistUser.setModifiedBy("SYSTEM");
                orderAssistUser.setOrderNo(order.getOrderNo());
                orderAssistUser.setStaffCode(e.getStaffCode());
                orderAssistUser.setAmibaName(e.getAmibaName());
                orderAssistUser.setStaffName(e.getStaffName());
                orderAssistUser.setAmibaId(e.getAmibaId());
                orderAssistUserMapper.insert(orderAssistUser);
            });
        }

        //添加协作人  如果订单的商务经理和跟单助理不是同一个人,将商务助理添加为订单的协作人
        if (Objects.nonNull(assistant) && !order.getBusinessAssistantStaffCode().equals(order.getBusinessManagerStaffCode())) {
            saveOrderAssistUser(order, assistant);
        }

        //新增入库消息提醒（已创建）
        MessageNotice messageNotice = new MessageNotice();
        messageNotice.setNoticeType(NoticeType.IN_STORAGE_NOTICE);
        messageNotice.setRelationData(OrderStatus.STATUS_CREATED.name());
        messageNotice.setToStaff(order.getBusinessManagerStaffCode());
        messageNotice.setContent(orderNo);
        messageNoticeService.add(messageNotice);
        try {
            commonLogService.add(CommonLogType.ORDER, CommonLogType.ORDER_ADD, order.getOrderNo(), "订单已提交", order.getCreatedBy());
        } catch (Exception e) {
            throw new CRMException("创建初始化日志失败", e);
        }

        OrderMemorandum orderMemorandum = new OrderMemorandum();
        orderMemorandum.setOrderNo(orderNo);
        orderMemorandum.setCustomerOrderNo(order.getCustomerOrderNo());
        orderMemorandum.setStaffName(BossConsts.BossSystem.NAME);
        orderMemorandum.setContent("新增交付订单 " + order.getName());
        orderMemorandum.setModifiedBy(BossConsts.BossSystem.NAME);
        orderMemorandum.setAvatarUrl(BossConsts.BossSystem.AVATAR_URL);
        orderMemorandumService.saveSystemLog(orderMemorandum);

        return orderNo;
    }

    /**
     * 根据订单号查询
     *
     * @param orderNo
     * @return
     */
    @Override
    public Order findByOrderNo(String orderNo) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order != null) {
            if (order.getLoanAmount() != null) {
                BigDecimal loanAmount = order.getLoanAmount();
                BigDecimal divide = loanAmount.divide(new BigDecimal(10000));
                order.setLoanAmount(divide);
            }
//            String mobile = order.getMobile();
//            if (StringUtils.isNotBlank(mobile)) {
//                order.setMobile(PrivacyDimmerUtils.maskMobile(mobile));
//            }
            if (StringUtils.isNotBlank(order.getBusinessManagerStaffCode()) && Objects.nonNull(order.getBusinessManagerAmibaId())) {
                //获取商务经理的信息
                //AmibaStaff businessManager = amibaStaffService.findSingleByStaffCode(order.getBusinessManagerStaffCode());
                AmibaStaff businessManager = amibaStaffService.findByStaffCodeAndAmibaId(order.getBusinessManagerStaffCode(), order.getBusinessManagerAmibaId());
                if (Objects.isNull(businessManager)) {
                    businessManager = amibaStaffService.findByStaffCodeAndAmibaId(order.getBusinessManagerStaffCode(),order.getBusinessManagerAmibaId());
                }
                if(Objects.nonNull(businessManager)){
                    order.setBusinessManagerMobile(businessManager.getStaffMobile());
                    order.setBusinessManagerId(businessManager.getId());
                    order.setBusinessManagerAmibaName(businessManager.getAmibaName());
                }
            }
            if (StringUtils.isNotBlank(order.getBusinessAssistantStaffCode())) {
                //获取跟单助理的信息
                AmibaStaff businessAssistant = amibaStaffService.findSingleByStaffCode(order.getBusinessAssistantStaffCode());
                if(Objects.nonNull(businessAssistant)){
                    order.setAssistantMobile(businessAssistant.getStaffMobile());
                    order.setBusinessAssistantId(businessAssistant.getId());
                }
            }
            if (StringUtils.isNotBlank(order.getDeliverManagerStaffCode())) {
                //获取交付经理的信息
                AmibaStaff deliverManager = amibaStaffService.findByStaffCodeAndAmibaId(order.getDeliverManagerStaffCode(),order.getDeliverManagerAmibaId());
                if(Objects.nonNull(deliverManager)){
                    order.setDeliverManagerMobile(deliverManager.getStaffMobile());
                    order.setDeliverManagerAmibaName(deliverManager.getAmibaName());
                }
            }

            if(Objects.nonNull(order.getDeliverBankId())){
                Bank bank = bankService.findById(order.getDeliverBankId());
                if(Objects.nonNull(bank)){
                    order.setBankLogo(bank.getBankIcon());
                    order.setBranchBankName(bank.getBankName());
                }
            }
        }
        return order;
    }

    /**
     * 添加协作人
     */
    private void saveOrderAssistUser(Order order, AmibaStaff assistant) {
        //先根据订单号去查询
        List<OrderAssistUser> orderAssistUserList = orderAssistUserMapper.selectByOrderNo(order.getOrderNo());
        List<String> collect = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orderAssistUserList)) {
            collect = orderAssistUserList.stream().map(OrderAssistUser::getStaffCode).collect(Collectors.toList());
            if (collect.contains(assistant.getStaffCode())) {
                return;
            }
        }
        OrderAssistUser orderAssistUser = new OrderAssistUser();
        orderAssistUser.setCreatedBy(order.getCurrentStaffName());
        orderAssistUser.setModifiedBy(order.getCurrentStaffName());
        orderAssistUser.setOrderNo(order.getOrderNo());
        orderAssistUser.setStaffCode(assistant.getStaffCode());
        orderAssistUser.setAmibaName(assistant.getAmibaName());
        orderAssistUser.setStaffName(assistant.getStaffName());
        orderAssistUser.setAmibaId(assistant.getAmibaId());
        orderAssistUserMapper.insert(orderAssistUser);
        // 新增订单协作人变更任务
        OrderTaskLog orderTaskLog = new OrderTaskLog();
        orderTaskLog.setModifiedBy(order.getCurrentStaffName());
        orderTaskLog.setOrderNo(order.getOrderNo());
        orderTaskLog.setType(OrderTaskLogType.ORDER_ASSIST_USER_CHANGE);
        orderTaskLog.setStaffCode(order.getCurrentStaffCode());
        try {
            orderTaskLog.setContent(JsonUtil.toJson(orderAssistUser));
        } catch (CRMException e) {

        }
        orderTaskLogMapper.insertSelective(orderTaskLog);
        //新增协作人记录
        OrderMemorandum orderMemorandum = new OrderMemorandum();
        orderMemorandum.setContent("新增协作人 " + assistant.getStaffName());
        orderMemorandum.setOrderNo(order.getOrderNo());
        orderMemorandum.setCustomerOrderNo(order.getCustomerOrderNo());
        orderMemorandum.setStaffName(order.getCurrentStaffName());
        orderMemorandum.setModifiedBy(order.getCurrentStaffName());
        orderMemorandum.setType(OrderMemorandumTypeEnum.LOG);
        //头像
        UserWechat userWechat = userWechatMapper.selectByStaffCode(order.getCurrentStaffCode());
        if (Objects.nonNull(userWechat) && StringUtils.isNotEmpty(userWechat.getAvatar())) {
            orderMemorandum.setAvatarUrl(userWechat.getAvatar());
        }
        orderMemorandumService.save(orderMemorandum);

        //消息体
        OrderCollaboratorMessage message = new OrderCollaboratorMessage();
        message.setCollaborator(assistant.getStaffName());
        List<String> staffCodes = new ArrayList<>();
        staffCodes.add(assistant.getStaffCode());
        message.setCollaboratorStaffCode(staffCodes);
        message.setFlag(0);
        message.setOperator(order.getCurrentStaffName());
        message.setName(order.getName());
        message.setOrderNo(order.getOrderNo());
        messageSendTaskService.save(MessageSendType.ORDER_COLLABORATOR_LOG_CHANGE_MSG, order.getOrderNo(), UUID.randomUUID().toString(), TopicConsts.WORK_ORDER_ORDER_ASSIST_USER_CHANGE, message);
    }

    /**
     * 更新订单
     *
     * @param order
     */
    @Override
    public void update(Order order) {

    }

    /**
     * 取消订单
     *
     * @param orderNo
     * @param currentName
     * @param currentStaffCode
     */
    @Override
    public void cancelOrder(String orderNo, String currentName, String currentStaffCode) {
        AssertUtils.notNull(orderNo, "订单号为空！");
        //原来的订单
        Order oldOrder = orderMapper.selectByOrderNo(orderNo);

        //first
        //更改订单状态为已取消
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setStatus(OrderStatus.STATUS_CANCEL);
        order.setInstoreTime(new Date());
        orderMapper.updateOrder(order);
        //取消订单的同时,把未完成的工单也取消
        List<WorkOrder> workOrders = workOrderService.findByOrderNo(orderNo);
        if (workOrders != null && workOrders.size() > 0) {
            for (WorkOrder workOrder : workOrders) {
                // 待分配   已分配
                if (workOrder.getStatus().equals(WorkOrderStatus.ASSIGNED) || workOrder.getStatus().equals(WorkOrderStatus.UN_ASSIGNEE)) {
                    //不取消私服工单
                    if(!workOrder.getWorkOrderTypeCode().equals(WorkOrderTypeCode.COMPANY_WRAP)){
                        workOrderService.cancel(workOrder.getWorkOrderNo(), currentName);
                    }
                }
            }
        }

        //添加取消订单同步任务
        OrderTaskLog orderTaskLog = new OrderTaskLog();
        orderTaskLog.setModifiedBy(currentName);
        orderTaskLog.setOrderNo(orderNo);
        orderTaskLog.setType(OrderTaskLogType.ORDER_STATUS_CHANGE);
        orderTaskLog.setStaffCode(currentStaffCode);
        try {
            orderTaskLog.setContent(JsonUtil.toJson(order));
        } catch (CRMException e) {

        }
        orderTaskLogMapper.insertSelective(orderTaskLog);

        //添加 发送到资产管理系统的kafka消息任务
        CancelOrderInfo2CapitalMessage cancelOrderInfo2CapitalMessage = new CancelOrderInfo2CapitalMessage();
        cancelOrderInfo2CapitalMessage.setOrderNo(orderNo);
        cancelOrderInfo2CapitalMessage.setProcessorCode(currentStaffCode);
        cancelOrderInfo2CapitalMessage.setProcessorName(currentName);

        cancelOrderInfo2CapitalMessage.setProcessTime(new Date());
        //消息通知任务日志
        messageSendTaskService.save(MessageSendType.JIAO_FU_ORDER_CANCELED,
                orderNo,
                orderNo+TopicConsts.CANCEL_ORDER_INFO_TO_CAPITAL_NOTIFY_TOPIC,
                TopicConsts.CANCEL_ORDER_INFO_TO_CAPITAL_NOTIFY_TOPIC,
                cancelOrderInfo2CapitalMessage);

        //second
        boolean toClear = false;
        //查询未结算的结算单 ps:这里可以优化，没有必要创建list对象
        List<WorkOrderSettle> workOrderSettles = workOrderSettleService.findByOrderNo(orderNo);
        if (Objects.nonNull(workOrderSettles) && workOrderSettles.size() > 0) {
            for (WorkOrderSettle workOrderSettle : workOrderSettles) {
                if (workOrderSettle.getOutsiteIncomeChargeAmount().intValue() > 0
                        || workOrderSettle.getOutsiteIncomeAmount().intValue() > 0
                        || workOrderSettle.getOutsiteIncomeChargeAmount().intValue() > 0) {
                    toClear = true;
                    break;
                }
            }
        }
        //查询订单的收支流水
        List<OrderCapitalDetail> orderCapitalDetails = orderCapitalDetailMapper.selectByOrderNo(orderNo);
        if (Objects.nonNull(orderCapitalDetails) && orderCapitalDetails.size() > 0) {
            toClear = true;
        }

        //生成订单清结算工单
        if (toClear) {
            workOrderService.create(orderNo, currentStaffCode, WorkOrderTypeCode.LIQUIDATION, "", currentName, null);
        }
        //新增入库消息提醒（已取消）
        MessageNotice messageNotice = new MessageNotice();
        messageNotice.setNoticeType(NoticeType.IN_STORAGE_NOTICE);
        messageNotice.setRelationData(order.getStatus().name());
        messageNotice.setToStaff(oldOrder.getBusinessManagerStaffCode());
        messageNotice.setContent(orderNo);
        messageNoticeService.add(messageNotice);
        //交付经理提醒
        if (StringUtils.isNotEmpty(oldOrder.getDeliverManagerStaffCode())) {
            messageNotice.setToStaff(oldOrder.getDeliverManagerStaffCode());
            messageNoticeService.add(messageNotice);
        }

        //自动更改当前订单上一个状态的未读信息为已读
        MessageNotice notice = new MessageNotice();
        notice.setContent(orderNo);
        notice.setToStaff(oldOrder.getBusinessManagerStaffCode());
        notice.setRelationData(oldOrder.getStatus().name());
        notice.setNoticeType(NoticeType.IN_STORAGE_NOTICE);
        notice.setReadStatus(1);
        messageNoticeService.updateStatus(notice);
        //交付经理
        if (StringUtils.isNotEmpty(oldOrder.getDeliverManagerStaffCode())) {
            notice.setToStaff(oldOrder.getDeliverManagerStaffCode());
            messageNoticeService.updateStatus(notice);
        }

        //记录订单修改日志
        try {
            commonLogService.add(
                    CommonLogType.ORDER,
                    CommonLogType.ORDER_STATUS_CHANGE,
                    orderNo,
                    "交付订单状态由[" + oldOrder.getStatusName() + "] 变更为[ " + order.getStatusName() + "]",
                    currentName);
        } catch (Exception e) {
            throw new CRMException("添加操作日志失败", e);
        }

        this.saveOrderMemorandum(orderNo, currentName, currentStaffCode, "交付订单状态由[" + oldOrder.getStatusName() + "] 变更为[ " + order.getStatusName() + "]");

    }

    private void saveOrderMemorandum(String orderNo, String staffName, String staffcode, String content) {
        OrderMemorandum orderMemorandum = new OrderMemorandum();
        orderMemorandum.setOrderNo(orderNo);
        orderMemorandum.setStaffName(staffName);
        orderMemorandum.setStaffCode(staffcode);
        orderMemorandum.setContent(content);
        orderMemorandum.setModifiedBy(staffName);
        orderMemorandumService.saveSystemLog(orderMemorandum);
    }

    /**
     * 根据客户订单号和交付巴ID查询交付订单
     *
     * @param customerOrderNo       客户订单号
     * @param deliverManagerAmibaId 交付巴ID
     * @return 交付订单
     */
    @Override
    public Order findByCustomerOrderNoAndDeliverManagerAmibaId(String customerOrderNo, Integer deliverManagerAmibaId) {
        AssertUtils.notNull(customerOrderNo,"客户订单号为空！");
        AssertUtils.notNull(deliverManagerAmibaId,"交付巴ID为空！");
        return orderMapper.selectByCustomerOrderNoAndDeliverManagerAmibaId(customerOrderNo,deliverManagerAmibaId);
    }

    /**
     * 根据客户订单号查询交付订单列表
     *
     * @param customerOrderNo
     */
    @Override
    public List<Order> findListByCustomerOrderNo(String customerOrderNo) {
        AssertUtils.notNull(customerOrderNo,"客户订单号为空！");
        return orderMapper.findByCustomerOrderNo(customerOrderNo);
    }

    @Override
    public void updateLxDeliverOrderId(String orderNo, Long lxId) {
        AssertUtils.hasText(orderNo, "订单号为空");
        AssertUtils.notNull(lxId, "励销交付订单id为Null");
        orderMapper.updateLxDeliverOrderId(orderNo, lxId);
    }

    @Override
    public void updateBank(String orderNo) {
        Order order = this.findByOrderNo(orderNo);
        Integer deliverManagerAmibaId = order.getDeliverManagerAmibaId();
        List<RelationAmibaBank> bankList = relationAmibaBankService.findAvailableBankListByAmibaId(deliverManagerAmibaId);
        if(CollectionUtils.isEmpty(bankList)){
            throw new CRMException("当前交付巴没有可用的银行，请手动修改启用的银行或与管理员联系");
        }
        this.updateBank(orderNo,bankList.get(0).getBankId());
    }

    @Override
    public void updateBank(String orderNo, Integer receiveAmibaBankId) {
        AssertUtils.notNull(orderNo,"订单号为空！");
        AssertUtils.notNull(receiveAmibaBankId,"银行ID为空！");
        orderMapper.updateBank(orderNo,receiveAmibaBankId);
    }

    /**
     * 更新
     *
     * @param order
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Order order) {
        AssertUtils.notNull(order, "要更新的订单为Null");
        AssertUtils.hasText(order.getOrderNo(), "修改订单号不能为空");

        Order oldOrder = findByOrderNo(order.getOrderNo());
        AssertUtils.notNull(oldOrder, "不存在该订单, 订单编号" + order.getOrderNo());

        order.setOriginalStatus(oldOrder.getStatus());
        orderMapper.updateOrder(order);

        try {
            commonLogService.add(
                    CommonLogType.ORDER,
                    CommonLogType.ORDER_STATUS_CHANGE,
                    order.getOrderNo(),
                    "订单状态由[" + oldOrder.getStatusName() + "] 变更为[ " + order.getStatusName() + "]",
                    order.getCreatedBy());
        } catch (Exception e) {
            throw new CRMException("添加操作日志失败", e);
        }

        Order order1 = orderMapper.selectByOrderNo(order.getOrderNo());
        customerOrderService.updateCustomerOrderFromDeliveryOrder(order1.getCustomerOrderNo(),order.getOperStaffCode(),order.getCreatedBy());

        // 保存消息体,kafka发送消息,用于订单状态变更对其他地方的影响
        OrderStatusChangeMessage message = new OrderStatusChangeMessage();
        message.setLxDeliverOrderId(oldOrder.getLxDeliverOrderId());
        message.setCustomerOrderNo(oldOrder.getCustomerOrderNo());
        message.setOrderNo(oldOrder.getOrderNo());
        message.setLoanUserName(oldOrder.getName());
        message.setOrigimalStatus(oldOrder.getStatus());
        message.setOriginalStatusName(oldOrder.getStatus().getValue());
        message.setTargetStatus(order.getStatus());
        message.setTargetStatusName(order.getStatus().getValue());
        message.setOperStaffCode(order.getOperStaffCode());
        message.setOperStaffName(order.getCreatedBy());
        messageSendTaskService.save(MessageSendType.ORDER_STATUS_CHANGE_MSG, order.getOrderNo(), UUID.randomUUID().toString(), TopicConsts.ORDER_STATUS_CHANGED, message);

        // 新增订单状态变更任务
//        OrderTaskLog orderTaskLog = new OrderTaskLog();
//        orderTaskLog.setModifiedBy(order.getCreatedBy());
//        orderTaskLog.setOrderNo(order.getOrderNo());
//        orderTaskLog.setType(OrderTaskLogType.ORDER_STATUS_CHANGE);
//        orderTaskLog.setStaffCode(order.getOperStaffCode());
//        try {
//            orderTaskLog.setContent(JsonUtil.toJson(order));
//        } catch (JsonProcessingException e) {
//
//        }
//        orderTaskLogMapper.insertSelective(orderTaskLog);
//
//        //新增入库消息提醒（变更后状态库）
//        MessageNotice messageNotice = new MessageNotice();
//        messageNotice.setNoticeType(NoticeType.IN_STORAGE_NOTICE);
//        messageNotice.setRelationData(order.getStatus().name());
//        messageNotice.setToStaff(oldOrder.getBusinessManagerStaffCode());
//        messageNotice.setContent(order.getOrderNo());
//        messageNoticeService.add(messageNotice);
//        //新增交付经理提醒
//        if (StringUtils.isNotEmpty(oldOrder.getDeliverManagerStaffCode())) {
//            messageNotice.setToStaff(oldOrder.getDeliverManagerStaffCode());
//            messageNoticeService.add(messageNotice);
//        }
//
//        //自动更改当前订单上一个状态的未读信息为已读
//        MessageNotice notice = new MessageNotice();
//        notice.setContent(order.getOrderNo());
//        notice.setToStaff(oldOrder.getBusinessManagerStaffCode());
//        notice.setRelationData(oldOrder.getStatus().name());
//        notice.setNoticeType(NoticeType.IN_STORAGE_NOTICE);
//        notice.setReadStatus(1);
//        messageNoticeService.updateStatus(notice);
//        //交付经理之前状态自动已读
//        if (StringUtils.isNotEmpty(oldOrder.getDeliverManagerStaffCode())) {
//            notice.setToStaff(oldOrder.getDeliverManagerStaffCode());
//            messageNoticeService.updateStatus(notice);
//        }

        //this.saveOrderMemorandum(order.getOrderNo(), order.getCreatedBy(), order.getOperStaffCode(), "订单状态由 " + oldOrder.getStatusName() + " 变为 " + order.getStatusName());
    }

    /**
     * 更新交付经理
     *
     * @param orderNo                 订单号
     * @param deliverManagerAmibaId   交付经理所属阿米巴
     * @param deliverManagerStaffCode
     * @param deliverManagerStaffName 交付经理
     * @param operator                操作人
     */
    @Override
    public void updateDeliverManager(String orderNo, Integer deliverManagerAmibaId, String deliverManagerStaffCode, String deliverManagerStaffName, String operator) {
        Order oldOrder = orderMapper.selectByOrderNo(orderNo);
        AssertUtils.notNull(oldOrder, "订单不存在");

        Order updateInfo = new Order();
        updateInfo.setOrderNo(orderNo);
        updateInfo.setDeliverManagerAmibaId(deliverManagerAmibaId);
        updateInfo.setDeliverManagerStaffCode(deliverManagerStaffCode);
        updateInfo.setDeliverManager(deliverManagerStaffName);
        updateInfo.setSubmitTime(new Date());
        orderMapper.updateOrder(updateInfo);

        try {
            commonLogService.add(
                    CommonLogType.ORDER,
                    CommonLogType.ORDER_MODIFY,
                    orderNo,
                    "订单交付经理由[" + (StringUtils.isEmpty(oldOrder.getDeliverManager()) ? "--" : oldOrder.getDeliverManager()) + "] 变更为[ " + deliverManagerStaffName + "]",
                    operator);
        } catch (Exception e) {
            throw new CRMException("添加操作日志失败", e);
        }
    }
}
